package com.china_goldcard.gridpagemenu;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jk on 16/10/22.
 */

public class GridFragmentAdapter extends FragmentStatePagerAdapter {

    protected List<GridFragment> dataList;

    protected Map<String,GridFragment> fragmentMaps = new HashMap<String,GridFragment>();

    public GridFragmentAdapter(FragmentManager fm, List<GridFragment> dataList) {
        super(fm);
        this.dataList = dataList;
    }

    @Override
    public Fragment getItem(int position) {
        GridFragment fragment = fragmentMaps.get(fragmentMapKey(position));
        if (fragment == null){
            fragment = dataList.get (position);
            fragmentMaps.put (fragmentMapKey(position), fragment);
        }
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container,position,object);
        fragmentMaps.remove (fragmentMapKey(position));
    }

    /**
     * index生成key
     * @param index
     * @return
     */
    private String fragmentMapKey(int index){
        return "FragmentMapKey" + index;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }
}
